import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'
import type { UserInfo } from './type'
import { getLoginAPI, getUserInfoAPI } from './apis'

export const useUserStore = defineStore('user', () => {
  let UserInfo = reactive({
    username: '',
    avatarUrl: '',
    token: localStorage.getItem('token'),
  })
  //账号密码登录
  const getLogin = async (data: UserInfo) => {
    const res = await getLoginAPI(data)

    if (res.code === 0) {
      UserInfo.token = res.data.token
      UserInfo = res.data
      localStorage.setItem('token', res.data.token)
    }
  }
  //获取用户信息
  const getUserInfo = async () => {
    const res = await getUserInfoAPI()
    if (res.code === 0) {
      UserInfo.username = res.data.username
      UserInfo.avatarUrl = res.data.avatarUrl
    }
  }
  //退出登录
  const logout = () => {
    UserInfo.username = ''
    UserInfo.avatarUrl = ''
    UserInfo.token = ''
    localStorage.removeItem('token')
  }
  return { UserInfo, getLogin, getUserInfo,logout }
})
